<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/12/3
 * Time: 14:00
 */
namespace app\autoreply\controller;

use app\common\config\autoreply_config;
use app\common\helper\autoreply_helper;
use app\common\model\Autoreply;
use app\common\model\AutoreplyContent;
use app\common\model\AutoreplyKey;
use think\facade\Request;
use app\admin\controller\AdminBase;

class Save extends AdminBase
{
    private $autoreply_type;

    /**
     * 保存自动回复
     */
    public function __call($action = '', $parmas = array())
    {
        $this->autoreply_type = autoreply_config::$autoreply_type;

        // 哪种的回复的保存(关注时，无法识别时)
        $autoreply_type = $action;
        if (!array_key_exists($autoreply_type.'', $this->autoreply_type)) {
            $autoreply_type = 1;
        }

        // 回复的文本的类型(纯文本，单图文，多图文)
        $content_type = Request::param('content_type', 0);

        // 关键词保存
        if ($autoreply_type == 3) {
            return $this->save_autokey();
        }

        // 回复的内容
        $content  = Request::param('content');

        $content = customer_content_filter($content);
        if (!$content) {
            return '回复内容不能为空';
        }

        if (in_array($content_type, array(2, 3))) {
            if (!is_numeric($content)) {
                return '选择的内容与类型不匹配';
            }

            $appmsg_info = _uri('appmsg', ['id' => $content]);
            if (!$appmsg_info) {
                return '选择的图文信息不存';
            }
        }

        // 主表
        $filter = array('company_id'=>$this->company_id, 'open_card_id'=>$this->open_card_id, 'type'=>$autoreply_type);
        $autoreply_id = _uri('autoreply', $filter, 'id');
        if (!$autoreply_id['id']) {
            $autoreply  = Autoreply::create($filter);
            $autoreply_id = $autoreply->id;
        }

        // 辅表
        $info = _uri('autoreply_content', array('autoreply_id'=>$autoreply_id));
        if (!$info) {
            AutoreplyContent::create([
                'autoreply_id' => $autoreply_id,
                'content_type' => $content_type,
                'content'      => html_entity_decode($content)
            ]);
        } else {
            AutoreplyContent::update(['content_type' => $content_type, 'content' => html_entity_decode($content)], ['autoreply_id' => $autoreply_id]);
        }

        if (Request::isAjax()) {
            return ['info' => 'ok'];
        }

        return redirect(url('/autoreply/admin/'.$autoreply_type));
    }

    /**
     * 保存关键词
     */
    private function save_autokey()
    {
        $id      = Request::param('id', 0);
        $title   = filter_string(Request::param('title'));
        $key     = Request::param('key', array());
        $info    = Request::param('info', array());

        if (!$title) {
            return ['info' => '关键词规则名不能为空'];
        }
        if (!$key) {
            return ['info' => '关键词不能为空'];
        }
        if (!$info) {
            return ['info' => '自动回复内容不能为空'];
        }

        if ($id) {
            Autoreply::update(['title'=>$title], ['id'=>$id]);
        } else {
            $autoreply = Autoreply::create([
                'company_id'   => $this->company_id,
                'open_card_id' => $this->open_card_id,
                'title'        => $title,
                'type'         => 3,
                'status'       => 1
            ]);

            $id = $autoreply->id;
        }

        // =========== 添加或更新key =====================================
        $old_key_ids = autoreply_helper::get_autoreply_key_ids($id);
        $update_ids  = array();

        $num = 0;
        foreach ($key as $k => $v) {
            if (isset($v['id']) && $v['id']) {
                AutoreplyKey::update($v,['id' => $v['id']]);
                array_push($update_ids, $v['id']);

            } else {
                AutoreplyKey::create([
                    'company_id'   => $this->company_id,
                    'open_card_id' => $this->open_card_id,
                    'autoreply_id' => $id,
                    'title'        => strip_tags($v['title']),
                    'match_type'   => (int)$v['match_type']
                ]);

            }

            $num++;
        }
        if (!$num) {
            return ['info' => '请至少填写一个关键词'];
        }

        // 去掉要删除的数据
        $delete_ids = array_diff($old_key_ids, $update_ids);
        if ($delete_ids && is_array($delete_ids)) {
            AutoreplyKey::destroy($delete_ids);
        }

        // =========== 添加或更新content =====================================
        $old_content_ids = autoreply_helper::get_autoreply_content_ids($id);
        $update_ids = array();
        $num = 0;
        foreach ($info as $k => $v) {
            $content = customer_content_filter($v['content']);
            if (!$content) {
                continue;
            }

            // 编辑
            if (isset($v['id']) && $v['id']) {
                AutoreplyContent::update(['content_type'=>$v['type'], 'content'=>$content], ['id'=>$v['id']]);

                array_push($update_ids, $v['id']);

                // 新增
            } else {
                AutoreplyContent::create([
                    'autoreply_id' => $id,
                    'content_type' => $v['type'],
                    'content'      => $content
                ]);
            }

            $num++;
        }
        if (!$num) {
            return ['info' => '请至少填写一个回复'];
        }

        // 去掉要删除的数据
        $delete_ids = array_diff($old_content_ids, $update_ids);
        //var_dump($delete_ids);
        if ($delete_ids && is_array($delete_ids)) {
            AutoreplyContent::destroy($delete_ids);
        }

        return ['info' => 'ok'];
    }
}